package com.harveyguo.nihonngo.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.harveyguo.nihonngo.model.dto.CourseCreateDto;
import com.harveyguo.nihonngo.model.dto.CourseDto;
import com.harveyguo.nihonngo.model.dto.WordDto;
import com.harveyguo.nihonngo.model.entity.Course;
import com.harveyguo.nihonngo.model.entity.Word;
import com.harveyguo.nihonngo.model.mapper.CourseMapper;
import com.harveyguo.nihonngo.model.mapper.UserMapper;
import com.harveyguo.nihonngo.repositories.CourseRepository;
import com.harveyguo.nihonngo.repositories.UserRepository;
import com.harveyguo.nihonngo.repositories.WordsRepository;
import com.harveyguo.nihonngo.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CourseServiceImpl implements CourseService {


    CourseRepository  courseRepository;
    WordsRepository wordsRepository;



    UserRepository  userRepository;

    CourseMapper courseMapper;

    @Override
    public List<CourseDto> list() {
        return this.courseRepository.findAll().stream().map(courseMapper::toDto).collect(Collectors.toList());
    }

    @Override
    public CourseDto createdCourse(CourseCreateDto createDto) {
        Course course = new Course();
        course.setName(createDto.getName());
        course.setUserId(StpUtil.getLoginId().toString());
        Course course1 =  courseRepository.save(course);

        // 设置单词列表
        List<Word> wordList = new ArrayList<>();

        for (WordDto wordDto : createDto.getWords()) {
            Word word = new Word();
            word.setName(wordDto.getName());
            word.setSpell(wordDto.getSpell());
            word.setDefinition(wordDto.getDefinition());
            word.setSentence(wordDto.getSentence());
            word.setCourse(course);
            wordList.add(word);
        }

        // 保存单词列表
        wordsRepository.saveAll(wordList);
        // 设置课程单词列表
        course.setWords(wordList);
//        this.userRepository.findByUsername()
        return  this.courseMapper.toDto(courseRepository.save(course)) ;
    }




    @Autowired
    public void setCourseRepository(CourseRepository courseRepository) {
        this.courseRepository = courseRepository;
    }

    @Autowired
    public void setCourseMapper(CourseMapper courseMapper) {
        this.courseMapper = courseMapper;
    }

    @Autowired
    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Autowired
    public void setWordsRepository(WordsRepository wordsRepository) {
        this.wordsRepository = wordsRepository;
    }
}
